import {
  hasOwnProperty,
  type Target,
} from './shallow-copy'
import { getType } from '@/library/libs/get-type'

/**
 * @description 深拷贝
 * @param {object | array} source 源对象
 * @returns {object | array} 新对象
 */
export function deepCopy(source: Target): Target {
  const type = getType(source)
  if (type === 'object' || type === 'array') {
    const target: Target = source instanceof Array ? [] : {}
    for (const key in source) {
      if (hasOwnProperty.call(source, key)) {
        target[key] = typeof source[key] === 'object' ? deepCopy(source[key]) : source[key]
      }
    }
    return target
  }

  return source
}

/**
 * @description 深拷贝数组或对象
 * @param {object | array} source 源对象
 * @returns {object | array} 新对象
 */
export function deepCopy2(source: Target): Target {
  const type = getType(source)

  if (type !== 'array' && type !== 'object') return source

  let target: Target

  const isArray = source instanceof Array

  if (isArray) {
    target = []
    for (const item of source) {
      target.push(deepCopy2(item))
    }
  } else {
    target = {}
    for (const key in source) {
      if (hasOwnProperty.call(source, key)) {
        target[key] = deepCopy2(source[key])
      }
    }
  }

  return target
}
